package com.example.system.controller;

import com.example.system.common.Result;
import com.example.system.entity.Health;
import com.example.system.service.impl.HealthServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@Controller
public class HealthFetchingWebSocketController {

    @Autowired
    private final SimpMessagingTemplate messagingTemplate;

    @Autowired
    HealthServiceImpl healthService;

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);

    private final Map<Integer, ScheduledFuture<?>> processesToPushHealth = new ConcurrentHashMap<>();

    public HealthFetchingWebSocketController(SimpMessagingTemplate messagingTemplate, HealthServiceImpl healthService) {
        this.messagingTemplate = messagingTemplate;
        this.healthService = healthService;
    }

    @MessageMapping("/startHealthPushing")
    public void startHealthPushing(@Payload Integer userId) {
        if (processesToPushHealth.containsKey(userId)) {
            return;
        }
        Runnable task = () -> {
            System.out.println("Pushing health data of ID: " + userId);
            try {
                TimeUnit.SECONDS.sleep(1); // 模拟任务执行时间
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            LocalDateTime beginTime = LocalDateTime.now().minusMinutes(1);
            LocalDateTime endTime = LocalDateTime.now();
            List<Health> healthList = healthService.findHealthByUserIDAndTimeRange(userId, beginTime, endTime);
            messagingTemplate.convertAndSend("/topic/pushHealth/" + userId, healthList);
        };
        ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
        processesToPushHealth.put(userId, future);
    }

    @MessageMapping("/stopHealthPushing")
    public void stopHealthPushing(@Payload Integer userId) {
        ScheduledFuture<?> future = processesToPushHealth.remove(userId);
        if (future != null && !future.isDone()) {
            future.cancel(false);
        }
    }
}